const Controller = require('egg').Controller;
const {  getCachedAccessToken } = require('../api/coze.js');

class UsersController extends Controller {
  /**
   * 头像上传接口
   */
  async uploadAvatar() {
    const { ctx, app } = this;
    const { file } = ctx.request.files;
    const { id } = ctx.currentUser;
    const filePath = file.path;
    const fileName = file.name;
    const fileType = file.type;
    const fileSize = file.size;
    const fileExt = fileName.split('.').pop();
    const fileNameWithoutExt = fileName.split('.').slice(0, -1).join('.');
    const filePathWithoutExt = filePath.split('.').slice(0, -1).join('.');
    // 保存图片到本地
    await ctx.service.file.saveFileToLocal(filePath, fileName, fileType, fileSize, fileExt, fileNameWithoutExt, filePathWithoutExt);
    ctx.body = {
      success: true,
      data: {
        avatar: `${ctx.config.baseUrl}/${filePathWithoutExt}.png`
      }
    };
  }

  /**
   * 获取我的下级会员列表。
   */
  async getMySonsUsers(){
    const { ctx, app } = this;
    let referrer_id = ctx.currentUser.id;
    // if(ctx.currentUser.is_admin === 1){
    //   referrer_id = 0;
    // }
    // 分页查询
    const { page = 1, pageSize = 10 } = ctx.query;
    const offset = (page - 1) * pageSize;
    console.log(offset)

    // 分页查询
    const users = await app.mysql.select('users', {
      where: {
        referrer_id,
      },
      columns: ['id', 'wx_name', 'vip_type', 'vip_expire_time','free_chat_number','referrer_id'],
      offset,
      limit: pageSize
    });
    ctx.body = {
      success: true,
      data: users
    };
  }

  /**
   * 登录接口
   * @returns {Promise<void>}
   */
  async login() {
    const { ctx, app } = this;
    const { code,referrer_id } = ctx.request.body;
    console.log(ctx.request.acceptJSON);
    
    console.log(code);
    
    if (!code) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '缺少code参数'
      };
      return;
    }

    try {
      // 调用微信接口获取openid和session_key
      const result = await ctx.curl('https://api.weixin.qq.com/sns/jscode2session', {
        data: {
          appid: 'wx9d31ca31d0c0966a', // 需要替换为您的小程序appid
          secret: '2c33d79645f87df8fea2be2a9ab570da', // 需要替换为您的小程序secret
          js_code: code,
          grant_type: 'authorization_code'
        },
        dataType: 'json'
      });

      const { openid, session_key, unionid } = result.data;

      if (!openid) {
        ctx.status = 400;
        ctx.body = {
          success: false,
          message: '微信登录失败',
          error: result.data.errmsg
        };
        return;
      }

      // 查询用户是否存在
      let user = await app.mysql.get('users', { wx_opneid:openid });

      // 如果用户不存在，创建新用户
      if (!user) {
        const userInfo = {
          wx_opneid:openid,
          wx_session_key:session_key,
          wx_unionid:unionid,
          wx_name:'微信用户',
          referrer_id:referrer_id??0
        };
        const result = await app.mysql.insert('users', userInfo);
        user = {
          id: result.insertId,
          ...userInfo
        };
      } else {
        // 如果用户存在，更新session_key
        await app.mysql.update('users', {
          id: user.id,
          wx_session_key:session_key,
          wx_unionid:unionid
        });
      }

      // 生成并保存token
      const token = await this.generateToken(user.id);

      ctx.body = {
        success: true,
        data: {
          token,
          user: {
            id: user.id,
          }
        }
      };
    } catch (error) {
      ctx.logger.error(error);
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '服务器错误',
        error: error.message
      };
    }
  }

  // 生成token并保存到数据库
  async generateToken(userId) {
    const { app } = this;
    const token = Buffer.from(`${userId}:${Date.now()}`).toString('base64');
    const expiredAt = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000); // 30天后过期

    await app.mysql.insert('users_token', {
      user_id: userId,
      token,
      expired_at: expiredAt
    });

    return token;
  }

  // 获取用户信息
  async getUserInfo() {
    const { ctx } = this;
    const userInfo = ctx.currentUser
    ctx.body = {
      success: true,
      data: userInfo
    };
  }

  // 更新用户信息
  async updateUserInfo() {
    const { ctx, app } = this;
    const updateData = ctx.request.body;
    
    // 防止更新敏感字段
    delete updateData.id;
    delete updateData.wx_opneid;
    delete updateData.wx_session_key;
    delete updateData.wx_unionid;
    try {
      await app.mysql.update('users', {
        ...updateData,
        id: ctx.currentUser.id
      });

      ctx.body = {
        success: true,
        message: '更新成功'
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '更新失败',
        error: error.message
      };
    }
  }

  /**
   * 设置个人访问令牌
   * coze_access_token
   */
  async setCozeAccessToken(){
    const {coze_access_token} = this.ctx.request.body;
    if(coze_access_token==='' || !coze_access_token){
      this.ctx.body = {
        success: false,
        message: '个人访问令牌不能为空'
      }
    }
    await this.app.mysql.update('users', {coze_access_token, id: this.ctx.currentUser.id});
    this.ctx.body = {
      success: true,
        message: '更新个人访问令牌成功'
    }
  }
  /**
   * 设置OAuth应用授权
   */
  async setCozeOAuth(){
    const {ctx,app} =this;

    const {coze_privateKey,publicKey} = ctx.request.body;
    if( !coze_privateKey || !publicKey){
      ctx.body = {
        success: false,
        message: 'OAuth应用授权信息不能为空'
      }
      return;
    }
    console.log('setCozeOAuth')

    const coze_access_token = await getCachedAccessToken(coze_privateKey, publicKey);
    console.log(`token获取成功：${coze_access_token}`)
    const resUpdateMysql = await app.mysql.update('users', {coze_access_token,coze_privateKey,coze_fingerprint:publicKey, id: ctx.currentUser.id});
    // 判断更新是否成功
    if(resUpdateMysql.affectedRows===0){
      ctx.body = {
        success: false,
        message: '更新OAuth应用授权失败'
      }
      return;
    }

    ctx.body = {
      success: true,
        message: '更新OAuth应用授权成功'
    }
  }


  // 退出登录
  async logout() {
    const { ctx, app } = this;
    const token = ctx.get('Authorization');
    
    if (token) {
      await app.mysql.delete('users_token', { token });
    }

    ctx.body = {
      success: true,
      message: '退出成功'
    };
  }

  /**
   * OAuth授权
   */
  async oauth(){

  }
}

module.exports = UsersController;
